package com.qfedu.common.redis.aspect;

import com.qfedu.common.redis.annotation.MyLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Classname LockAspect
 * @Description TODO
 * @Date 2025-09-28 15:13
 * @Created by 老任与码
 */
@Aspect
@Component
public class LockAspect {

    @Resource
    private RedissonClient redissonClient;

    @Pointcut("@annotation(com.qfedu.common.redis.annotation.MyLock)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodInvocationProceedingJoinPoint mjp = (MethodInvocationProceedingJoinPoint) joinPoint;
        MethodSignature signature = (MethodSignature) mjp.getSignature();
        Method method = signature.getMethod();

        // 获取指定的注解对象
        MyLock annotation = method.getAnnotation(MyLock.class);
        if (annotation != null) {
            RLock lock = redissonClient.getLock(annotation.lockName());
            try {
                if (lock.tryLock(annotation.waitTime(), annotation.leaseTime(), TimeUnit.SECONDS)) {
                    // 执行目标方法
                    return joinPoint.proceed();
                }
            } catch (Throwable e) {
                throw new RuntimeException(e);
            } finally {
                if (lock.isHeldByCurrentThread() && lock.isLocked()) {
                    lock.unlock();
                }
            }
        }
        return joinPoint.proceed();
    }
}
